<template>
  <div class="SongSheetCotent">
    <div class="SongSheetMain">
      <van-nav-bar>
        <template #left>
          <van-icon name="arrow-left" @click="fanhui" />
          歌单广场
        </template>
      </van-nav-bar>
      <van-tabs
        v-model="active"
        animated
        swipeable
        sticky
        @change="onClickLoad"
      >
        <van-tab
          v-for="(item, index) in tags"
          :name="index"
          :title="item.name"
          :key="index"
          class="tabsList"
        >
          <van-list
            v-model="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="getLoad"
          >
            <van-row class="detailsCotent" type="flex" gutter="15">
              <van-col
                span="8"
                v-for="item in sub"
                :key="item.id"
                @click="clickCol(item)"
              >
                <van-image :src="item.coverImgUrl" lazy-load :loading="pic">
                  <template>
                    <div class="musicUpdatemsg">{{ item.updateFrequency }}</div>
                  </template>
                </van-image>
                <div class="imgTitle">{{ item.name }}</div>
              </van-col>
            </van-row>
          </van-list>
        </van-tab>
        <template v-slot:nav-right>
          <van-icon
            name="apps-o"
            class="breadButton"
            @click="showCategoriesPopuop"
          />
        </template>
      </van-tabs>
      <!-- 弹层用于修改我的歌单列表 -->
      <van-popup
        v-model="categoriesPopuop"
        position="right"
        :style="{ height: '100%', width: '100%' }"
      >
        <van-nav-bar
          left-text="歌单标签"
          left-arrow
          @click-left="closeCategoriesPopuop"
        />
        <van-cell title="我的歌单广场">
          <template #right-icon>
            <van-button plain type="danger" round size="mini" @click="editTags">
              {{ showEditTags ? '完成' : '编辑' }}
            </van-button>
          </template>
        </van-cell>
        <van-row type="flex" align="center" gutter="15" class="cateListContent">
          <van-col
            span="6"
            van-row
            type="flex"
            justify="center"
            align="center"
            v-for="(item, index) in tags"
            :key="index"
            class="cateList"
          >
            <van-button
              :class="{ redBtn: active === index }"
              style="background-color: #f8f8f8; height: 32px; width: 80px; white-space: nowrap; font-size:12px"
              round
              @click="clickMyTags(item)"
            >
              <template v-slot:default>
                <van-icon
                  name="fire-o"
                  color="#ee0a24"
                  v-if="!showEditTags"
                  v-show="item.hot"
                />
                <van-icon name="minus" v-else />
                {{ item.name }}
              </template>
            </van-button>
          </van-col>
        </van-row>
        <div v-for="title in categoriesList" :key="title.id">
          <van-cell :title="title.categories" />
          <van-row
            type="flex"
            align="center"
            gutter="15"
            class="cateListContent"
          >
            <van-col
              span="6"
              van-row
              type="flex"
              justify="center"
              align="center"
              v-for="(item, index) in title.children"
              :key="index"
              class="cateList"
            >
              <van-button
                type="default"
                style="background-color: #f8f8f8; height: 32px; width: 80px; white-space: nowrap; font-size:12px"
                round
                @click="addTags(item)"
                :disabled="isDisableb(item)"
              >
                <template v-slot:default>
                  <van-icon
                    name="fire-o"
                    color="#ee0a24"
                    v-if="!showEditTags"
                    v-show="item.hot"
                  />
                  <van-icon name="plus" v-else />
                  {{ item.name }}
                </template>
              </van-button>
            </van-col>
          </van-row>
        </div>
      </van-popup>
    </div>
    <list-components
      :ListComponentsShow.sync="ListComponentsShow"
      :id="id"
    ></list-components>
  </div>
</template>

<script>
import { getHot, getRecommend, getCatlist } from '@/api/SongSheet'
import { getItem, setItem } from '@/utils/storage'
import loading from '@/assets/loading.jpg'
import axios from 'axios'
export default {
  name: 'SongSheet',
  data () {
    return {
      catlist: {},
      categoriesList: {},
      active: 0,
      activekey: 0,
      sub: [], // 渲染的歌单内容
      subCategories: {},
      tags: [{ name: '推荐' }], // 我的歌单列表
      categories: {}, // 歌单的分类
      loading: false,
      finished: false,
      limit: 20,
      page: 1,
      total: 0,
      throttle: true, // 节流阀
      showPopup: false,
      categoriesPopuop: false,
      showEditTags: false,
      ListComponentsShow: false,
      id: 0,
      pic: loading
    }
  },
  watch: {
    tags: {
      handler: function (val) {
        setItem('tags', val)
      },
      deep: true
    }
  },
  created () {
    this.getHot()
    this.getRecommend()
  },
  methods: {
    // 获取我的歌单广场
    async getHot () {
      this.catlist = await getHot()
      const { tags } = this.catlist
      console.log(...this.tags)
      // console.log(...tags)
      this.tags = getItem('tags') || [...this.tags, ...tags]
    },
    async getRecommend (id) {
      try {
        const { playlists, total } = await getRecommend(id)
        this.total = total
        this.sub = [...this.sub, ...playlists]
        const obj = {}
        this.sub = this.sub.reduce((cur, next) => {
          if (!obj[next.id]) {
            obj[next.id] = true && cur.push(next)
          }
          return cur
        }, [])
      } catch (error) {
        console.log(error)
      }
    },
    onClickLoad (name, title) {
      axios.CancelToken.source().cancel('取消请求')
      this.page = 1
      this.sub = []
      this.title = title
      this.loading = false
      if (title === '推荐') {
        return this.getRecommend()
      }
      this.getRecommend({
        cat: this.title,
        limit: this.limit,
        offset: this.page - 1
      })
    },
    getLoad () {
      console.log(
        '触发了 Loading: ' + this.loading + ' finished:' + this.finished
      )
      this.page++
      const offset = (this.page - 1) * this.limit
      function debounce (fn, wait) {
        var timer = null
        return function () {
          if (timer !== null) {
            clearTimeout(timer)
          }
          timer = setTimeout(fn, wait)
        }
      }
      debounce(
        this.getRecommend({
          cat: this.title,
          limit: this.limit,
          offset: offset
        }),
        1000
      )

      setTimeout(() => {
        this.loading = false
        if (this.sub.length === this.total) {
          this.finished = true
        }
      }, 1000)
    },
    async showCategoriesPopuop () {
      const obj = await getCatlist()
      const cateList = []
      const { categories, sub } = obj
      for (const key in categories) {
        cateList.push({ id: key, categories: categories[key], children: [] })
      }
      sub.forEach(item => {
        cateList.forEach(element => {
          if (parseInt(element.id) === parseInt(item.category)) {
            element.children.push(item)
          }
        })
      })
      this.categoriesList = cateList
      this.categoriesPopuop = true
    },
    closeCategoriesPopuop () {
      this.categoriesPopuop = false
    },
    isDisableb (item) {
      return this.tags.some(element => item.name === element.name)
      // console.log(item)
    },
    editTags () {
      this.showEditTags = !this.showEditTags
    }, // 修改我的歌单广场
    clickMyTags (item) {
      if (this.showEditTags) {
        console.log('删除')
        this.tags.forEach((element, index) => {
          if (element.name === item.name) {
            this.tags.splice(index, 1)
            if (this.active === index) {
              this.active--
            }
            if (index < this.active) {
              this.active--
            }
          }
        })
      } else {
        this.active = this.tags.findIndex(element => element.name === item.name)
        // console.log(this.active, item.name)
        this.onClickLoad(this.active, item.name)
        this.categoriesPopuop = false
      }
    }, // 增加新的歌单类型
    addTags (item) {
      if (this.showEditTags) {
        this.tags.push(item)
      } else {
        this.tags.push(item)
        this.$nextTick(_ => {
          this.clickMyTags(item)
        })
      }
    },
    clickCol (item) {
      this.id = item.id
      this.ListComponentsShow = true
    },
    fanhui () {
      axios.CancelToken.source().cancel('取消请求')

      this.$router.go(-1)
    }
  }
}
</script>

<style scoped lang="less">
.SongSheetMain {
  /deep/.van-nav-bar__text {
    color: black;
    line-height: normal !important;
  }
  /deep/.van-icon {
    color: black;
  }
  .van-col .van-image {
    display: block;
    position: relative;
    /deep/img {
      display: block;
      border-radius: 10px;
    }
  }
  /deep/.musicUpdatemsg {
    position: absolute;
    color: #fff;
    bottom: 10px;
    left: 20px;
    font-size: 24px;
  }
  .van-row .imgTitle {
    font-size: 12px;
    // max-width: 200px;
    height: 100px;
    line-height: 50px;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
    margin: 0 auto;
    padding-bottom: 10px;
  }
  .detailsCotent {
    padding: 20px;
  }
  .breadButton {
    position: fixed;
    right: 0;
    width: 88px;
    height: 88px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff;
    opacity: 0.95;
    flex-shrink: 0;
  }
  .cateListContent {
    padding: 20px 32px;
  }
  .cateList {
    margin: 10px 0;
  }
  /deep/.van-sticky {
    padding-right: 88px;
  }
  /deep/.redBtn {
    border-color: rgb(238, 10, 36) !important;
    color: rgb(238, 10, 36);
  }
}
</style>
